//
//  MYGUserManager.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/11.
//

import UIKit

class MYGUserManager: NSObject {
    static var isLogin: Bool {
        user != nil
    }
    static var _isDoctorInfComplete: Bool?
    static var isDoctorInfComplete: Bool  {
        get{
            let isSuc = (MYGUserManager.user?.doctor.card_images.count)! > 1 && (MYGUserManager.user?.doctor.professional.count)! > 0 && (MYGUserManager.user?.doctor.qualification.count)! > 0
            return isSuc
        }
        set {
            _isDoctorInfComplete = newValue
        }
    }
    static var user: MYGUserModel? {
        get {
            getUser()
        }
        set {
            guard let newValue = newValue else {
                removeUser()
                return
            }
            
            saveUser(newValue)
        }
    }
    
    private static let filePath = "MYGUserMessage"

    
    static func saveUser(_ model: MYGUserModel) {
        removeUser()
        let file_path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent(filePath)
        guard let data = model.toJSON()?.jsonData() else {
            return
        }
        
        do {
            try data.write(to: URL(fileURLWithPath: file_path))
        } catch {
            print("用户数据保存失败")
        }
    }
    
    static func getUser() -> MYGUserModel? {
        let file_path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent(filePath)
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: file_path))
            let json = String(data: data, encoding: .utf8)
            let model = MYGUserModel.deserialize(from: json?.dic)
            return model
        } catch {
            print("数据获取失败")
            return nil
        }
    }
    
    static func removeUser() {
        let file_path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent(filePath)
        do {
           try FileManager.default.removeItem(atPath: file_path)
        } catch {
            print("用户数据删除失败")
        }
    }
}
